package com.iot.manager.ui.activities;

import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.OpenableColumns;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.IndexAxisValueFormatter;
import com.github.mikephil.charting.formatter.ValueFormatter;
import com.google.android.material.button.MaterialButton;
import com.google.android.material.chip.Chip;
import com.google.android.material.chip.ChipGroup;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import com.google.android.material.textfield.TextInputEditText;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.iot.manager.R;
import com.iot.manager.ui.adapters.DeviceDataAdapter;
import com.iot.manager.data.models.Device;
import com.iot.manager.data.models.DeviceConfig;
import com.iot.manager.data.models.DeviceData;
import com.iot.manager.network.ApiService;
import com.iot.manager.network.RetrofitClient;
import com.iot.manager.network.WebSocketClient;
import com.iot.manager.ui.fragments.DeviceDataFragment;
import com.iot.manager.utils.DataExporter;
import com.google.android.material.datepicker.MaterialDatePicker;
import com.google.android.material.datepicker.CalendarConstraints;
import com.google.android.material.datepicker.DateValidatorPointForward;
import com.iot.manager.ui.adapters.DeviceDataAdapter;
import com.iot.manager.utils.DateUtils;
import com.iot.manager.ui.dialogs.EditDeviceDialog;
import com.iot.manager.ui.dialogs.SendCommandDialog;
import com.iot.manager.ui.dialogs.DeviceControlDialog;
import com.iot.manager.utils.SharedPreferencesManager;
import com.iot.manager.network.WebSocketManager;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import androidx.core.content.FileProvider;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import java.util.Collections;
import android.content.SharedPreferences;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;
import org.json.JSONException;
import org.json.JSONObject;

public class DeviceDetailActivity extends AppCompatActivity implements WebSocketManager.DeviceStatusListener, WebSocketManager.DeviceDataListener {
    private static final String TAG = "DeviceDetailActivity";
    private static final int UPDATE_INTERVAL = 5000; // 5秒更新一次
    private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("MM-dd HH:mm", Locale.getDefault());
    private static final SimpleDateFormat CHART_DATE_FORMAT = new SimpleDateFormat("HH:mm", Locale.getDefault()); // For chart X-axis
    private static final SimpleDateFormat DATE_RANGE_FORMAT = new SimpleDateFormat("MM-dd", Locale.getDefault());
    private static final int PICK_FIRMWARE_FILE = 1001;
    private static final String PREF_NAME = "device_detail_pref";
    private static final String KEY_START_TIME = "start_time";
    private static final String KEY_END_TIME = "end_time";
    private static final String WS_URL = "ws://localhost:3001/ws";

    private Toolbar toolbar;
    private TextView tvDeviceName;
    private TextView tvDeviceId;
    private TextView tvFirmwareVersion;
    private Chip chipStatus;
    private TextView tvTemperature;
    private TextView tvHumidity;
    private LineChart lineChart;
    private MaterialButton btnDateFilter;
    private ProgressBar progressBar;
    private String deviceId;
    private Handler handler;
    private Runnable updateRunnable;
    private ApiService apiService;
    private List<DeviceData> dataList = new ArrayList<>();
    private Date startTime;
    private Date endTime;
    private List<Integer> selectedDataTypes;
    private Device device;
    private FloatingActionButton fabExport;
    private DeviceDataFragment deviceDataFragment;
    private WebSocketClient webSocketClient;
    private MaterialButton btnSendCommand;
    private MaterialButton btnUpdateFirmware;
    private MaterialButton btnEditConfig;
    private MaterialButton btnEditThresholds;
    private Date startDate;
    private Date endDate;
    private RecyclerView recyclerView;
    private DeviceDataAdapter deviceDataAdapter;
    private MaterialButton btnEditDevice;
    private MaterialButton btnPrevPage;
    private MaterialButton btnNextPage;
    private TextView tvPageInfo;
    private WebSocket webSocket;
    private OkHttpClient wsClient;
    private TextView tvDeviceType;
    private TextView tvLastHeartbeat;
    private TextView tvDeviceStatus;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_device_detail);

        // 获取设备ID
        deviceId = getIntent().getStringExtra("deviceId");
        if (deviceId == null || deviceId.isEmpty()) {
            Toast.makeText(this, "设备ID不能为空", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }

        apiService = RetrofitClient.getInstance().getApiService();
        handler = new Handler();

        // 初始化WebSocket客户端
        wsClient = new OkHttpClient.Builder()
                .readTimeout(0, TimeUnit.MILLISECONDS)
                .build();

        // 初始化日期范围
        loadDateRange();
        if (startTime == null || endTime == null) {
            Calendar calendar = Calendar.getInstance();
            calendar.set(Calendar.HOUR_OF_DAY, 0);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
            calendar.set(Calendar.MILLISECOND, 0);
            startTime = calendar.getTime();
            
            calendar.set(Calendar.HOUR_OF_DAY, 23);
            calendar.set(Calendar.MINUTE, 59);
            calendar.set(Calendar.SECOND, 59);
            endTime = calendar.getTime();
        }

        initViews();
        setupToolbar();
        setupDateRangePicker();
        setupRecyclerView();
        setupChart();
        setupButtons();
        
        updateDateRangeButton();
        
        // 首次加载数据
        loadData();
        
        // 连接WebSocket
        connectWebSocket();

        // 注册WebSocket监听器
        WebSocketManager.getInstance(this).addStatusListener(this);
        WebSocketManager.getInstance(this).addDataListener(this);
    }

    private void initViews() {
        toolbar = findViewById(R.id.toolbar);
        if (toolbar != null) {
            setSupportActionBar(toolbar);
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setTitle("设备详情");
        }

        tvDeviceName = findViewById(R.id.tv_device_name);
        tvDeviceId = findViewById(R.id.tvDeviceId);
        tvFirmwareVersion = findViewById(R.id.tvFirmwareVersion);
        tvDeviceStatus = findViewById(R.id.tvDeviceStatus);
        tvTemperature = findViewById(R.id.tv_temperature);
        tvHumidity = findViewById(R.id.tv_humidity);
        lineChart = findViewById(R.id.chart);
        recyclerView = findViewById(R.id.recyclerView);
        progressBar = findViewById(R.id.progressBar);
        fabExport = findViewById(R.id.fabExport);
        btnDateFilter = findViewById(R.id.btn_date_filter);
        btnPrevPage = findViewById(R.id.btnPrevPage);
        btnNextPage = findViewById(R.id.btnNextPage);
        tvPageInfo = findViewById(R.id.tvPageInfo);
        tvDeviceType = findViewById(R.id.tvDeviceType);
        tvLastHeartbeat = findViewById(R.id.tvLastHeartbeat);

        // 设置按钮点击事件
        setupListeners();
    }

    private void setupListeners() {
        if (btnEditDevice != null) {
            btnEditDevice.setOnClickListener(v -> showEditDeviceDialog());
        }
        if (btnSendCommand != null) {
            btnSendCommand.setOnClickListener(v -> showSendCommandDialog());
        }
        if (btnUpdateFirmware != null) {
            btnUpdateFirmware.setOnClickListener(v -> showUpdateFirmwareDialog());
        }
        if (btnDateFilter != null) {
            btnDateFilter.setOnClickListener(v -> showDateRangePicker());
        }
        if (fabExport != null) {
            fabExport.setOnClickListener(v -> exportData());
        }
        if (btnPrevPage != null) {
            btnPrevPage.setOnClickListener(v -> {
                deviceDataAdapter.previousPage();
                updatePageInfo();
            });
        }
        if (btnNextPage != null) {
            btnNextPage.setOnClickListener(v -> {
                deviceDataAdapter.nextPage();
                updatePageInfo();
            });
        }
    }

    private void setupChart() {
        lineChart.getDescription().setEnabled(false);
        lineChart.setTouchEnabled(true);
        lineChart.setDragEnabled(true);
        lineChart.setScaleEnabled(true);
        lineChart.setPinchZoom(true);
        lineChart.setDrawGridBackground(false);
        lineChart.setDrawBorders(false);
        lineChart.setNoDataText("暂无数据");
        lineChart.setNoDataTextColor(getResources().getColor(android.R.color.darker_gray));
        
        // 设置图例
        Legend legend = lineChart.getLegend();
        legend.setEnabled(true);
        legend.setTextSize(12f);
        legend.setFormSize(12f);
        legend.setFormToTextSpace(5f);
        legend.setHorizontalAlignment(Legend.LegendHorizontalAlignment.RIGHT);
        legend.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
        legend.setOrientation(Legend.LegendOrientation.HORIZONTAL);
        legend.setDrawInside(false);
        
        // 设置X轴
        XAxis xAxis = lineChart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setDrawGridLines(true);
        xAxis.setLabelRotationAngle(-45f);
        xAxis.setValueFormatter(new ValueFormatter() {
            @Override
            public String getFormattedValue(float value) {
                Date date = new Date((long) value);
                SimpleDateFormat sdf = new SimpleDateFormat("MM-dd HH:mm", Locale.getDefault());
                return sdf.format(date);
            }
        });
        xAxis.setGranularityEnabled(true);
        
        // 设置Y轴
        YAxis leftAxis = lineChart.getAxisLeft();
        leftAxis.setDrawGridLines(true);
        leftAxis.setAxisMinimum(0f);
        leftAxis.setAxisMaximum(100f);
        
        YAxis rightAxis = lineChart.getAxisRight();
        rightAxis.setEnabled(false);
    }

    private void loadDeviceData() {
        showLoading(true);
        apiService.getDevice(deviceId).enqueue(new Callback<Device>() {
            @Override
            public void onResponse(Call<Device> call, Response<Device> response) {
                showLoading(false);
                if (response.isSuccessful() && response.body() != null) {
                    updateDeviceInfo(response.body());
                } else {
                    showError("获取设备信息失败");
                }
            }

            @Override
            public void onFailure(Call<Device> call, Throwable t) {
                showLoading(false);
                showError("网络错误：" + t.getMessage());
            }
        });
    }

    private void updateDeviceInfo(Device device) {
        this.device = device;
        updateUI();
        loadHistoryData();
    }

    private void updateUI() {
        if (device != null) {
            setTitle(device.getName());
            
            // 检查视图是否为空
            View deviceNameView = findViewById(R.id.tv_device_name);
            View deviceIdView = findViewById(R.id.tvDeviceId);
            View firmwareVersionView = findViewById(R.id.tvFirmwareVersion);
            
            if (deviceNameView != null) deviceNameView.setVisibility(View.VISIBLE);
            if (deviceIdView != null) deviceIdView.setVisibility(View.VISIBLE);
            if (firmwareVersionView != null) firmwareVersionView.setVisibility(View.VISIBLE);
            
            // 更新设备ID
            if (tvDeviceId != null) {
                tvDeviceId.setText(device.getDeviceId() != null ? device.getDeviceId() : "未获取到");
            }
            
            // 更新设备类型
            if (tvDeviceType != null) {
                tvDeviceType.setText(device.getType() != null ? device.getType() : "未获取到");
            }
            
            // 更新设备状态
            String status = device.getStatus() != null ? device.getStatus() : "offline";
            if (tvDeviceStatus != null) {
                tvDeviceStatus.setText(status.equals("online") ? "在线" : "离线");
                tvDeviceStatus.setBackgroundResource(status.equals("online") ? 
                    R.color.online : R.color.offline);
            }
            
            // 更新最后心跳时间
            if (tvLastHeartbeat != null) {
                if (device.getLastHeartbeat() != null && !device.getLastHeartbeat().isEmpty()) {
                    try {
                        // 使用 ISO 8601 格式解析日期
                        SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.getDefault());
                        inputFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
                        SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
                        outputFormat.setTimeZone(TimeZone.getDefault());
                        
                        Date date = inputFormat.parse(device.getLastHeartbeat());
                        if (date != null) {
                            tvLastHeartbeat.setText(outputFormat.format(date));
                        } else {
                            tvLastHeartbeat.setText("未获取到");
                        }
                    } catch (ParseException e) {
                        tvLastHeartbeat.setText("未获取到");
                    }
                } else {
                    tvLastHeartbeat.setText("未获取到");
                }
            }
            
            // 更新设备名称
            if (tvDeviceName != null) {
                tvDeviceName.setText(device.getName() != null ? device.getName() : "未命名设备");
            }
            
            // 只在设备在线时显示固件版本
            if (tvFirmwareVersion != null) {
                if (status.equals("online")) {
                    tvFirmwareVersion.setText(device.getFirmwareVersion() != null ? device.getFirmwareVersion() : "未获取到");
                } else {
                    tvFirmwareVersion.setText("设备离线");
                }
            }
            
            // 更新温度和湿度
            if (tvTemperature != null) {
                if (device.getTemperature() != null) {
                    tvTemperature.setText(String.format("%.1f°C", device.getTemperature()));
                } else {
                    tvTemperature.setText("未获取到");
                }
            }
            
            if (tvHumidity != null) {
                if (device.getHumidity() != null) {
                    tvHumidity.setText(String.format("%.1f%%", device.getHumidity()));
                } else {
                    tvHumidity.setText("未获取到");
                }
            }
        }
    }

    private void loadHistoryData() {
        showLoading(true);
        apiService.getDeviceData(deviceId, startTime, endTime).enqueue(new Callback<List<DeviceData>>() {
            @Override
            public void onResponse(Call<List<DeviceData>> call, Response<List<DeviceData>> response) {
                showLoading(false);
                if (response.isSuccessful() && response.body() != null) {
                    List<DeviceData> data = response.body();
                    dataList.clear();
                    dataList.addAll(data);
                    updateChart(data);
                    deviceDataAdapter.updateData(data); // 更新数据表格
                } else {
                    showError("加载历史数据失败");
                }
            }

            @Override
            public void onFailure(Call<List<DeviceData>> call, Throwable t) {
                showLoading(false);
                showError("加载历史数据失败：" + t.getMessage());
            }
        });
    }

    private void updateChart(List<DeviceData> data) {
        if (data == null || data.isEmpty()) {
            lineChart.clear();
            lineChart.invalidate();
            return;
        }

        // 按时间排序
        Collections.sort(data, (d1, d2) -> {
            if (d1.getTimestamp() == null || d2.getTimestamp() == null) {
                return 0;
            }
            return d1.getTimestamp().compareTo(d2.getTimestamp());
        });

        List<Entry> temperatureEntries = new ArrayList<>();
        List<Entry> humidityEntries = new ArrayList<>();
        
        for (DeviceData point : data) {
            if (point.getTimestamp() != null) {
                long timestamp = point.getTimestamp().getTime();
                if (point.getTemperature() != null) {
                    temperatureEntries.add(new Entry(timestamp, point.getTemperature().floatValue()));
                }
                if (point.getHumidity() != null) {
                    humidityEntries.add(new Entry(timestamp, point.getHumidity().floatValue()));
                }
            }
        }
        
        LineDataSet temperatureDataSet = new LineDataSet(temperatureEntries, "温度");
        temperatureDataSet.setColor(getResources().getColor(R.color.colorTemperature));
        temperatureDataSet.setCircleColor(getResources().getColor(R.color.colorTemperature));
        temperatureDataSet.setDrawValues(false);
        temperatureDataSet.setMode(LineDataSet.Mode.LINEAR);
        temperatureDataSet.setLineWidth(2f);
        temperatureDataSet.setCircleRadius(4f);
        temperatureDataSet.setDrawCircleHole(false);
        temperatureDataSet.setDrawCircles(false);
        
        LineDataSet humidityDataSet = new LineDataSet(humidityEntries, "湿度");
        humidityDataSet.setColor(getResources().getColor(R.color.colorHumidity));
        humidityDataSet.setCircleColor(getResources().getColor(R.color.colorHumidity));
        humidityDataSet.setDrawValues(false);
        humidityDataSet.setMode(LineDataSet.Mode.LINEAR);
        humidityDataSet.setLineWidth(2f);
        humidityDataSet.setCircleRadius(4f);
        humidityDataSet.setDrawCircleHole(false);
        humidityDataSet.setDrawCircles(false);
        
        LineData lineData = new LineData(temperatureDataSet, humidityDataSet);
        lineChart.setData(lineData);
        lineChart.invalidate();
    }

    private void exportData() {
        if (dataList.isEmpty()) {
            Toast.makeText(this, "没有可导出的数据", Toast.LENGTH_SHORT).show();
            return;
        }

        // 根据当前时间范围筛选数据
        List<DeviceData> filteredData = dataList.stream()
                .filter(data -> {
                    Date timestamp = data.getTimestamp();
                    return timestamp.after(startTime) && timestamp.before(endTime);
                })
                .collect(Collectors.toList());

        if (filteredData.isEmpty()) {
            Toast.makeText(this, "所选时间范围内没有数据", Toast.LENGTH_SHORT).show();
            return;
        }

        try {
            File exportFile = DataExporter.exportToCsv(this, filteredData, deviceId);
            if (exportFile != null) {
                // 创建文件URI
                Uri fileUri = FileProvider.getUriForFile(this,
                        getApplicationContext().getPackageName() + ".provider",
                        exportFile);

                // 创建分享Intent
                Intent shareIntent = new Intent(Intent.ACTION_SEND);
                shareIntent.setType("text/csv");
                shareIntent.putExtra(Intent.EXTRA_STREAM, fileUri);
                shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

                // 显示分享对话框
                startActivity(Intent.createChooser(shareIntent, "分享数据文件"));
                
                Toast.makeText(this, "数据已导出到: " + exportFile.getAbsolutePath(), Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(this, "导出失败", Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            Log.e(TAG, "导出数据失败", e);
            Toast.makeText(this, "导出失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    private void showDateRangePicker() {
        MaterialDatePicker<androidx.core.util.Pair<Long, Long>> dateRangePicker = MaterialDatePicker.Builder.dateRangePicker()
                .setTitleText("选择日期范围")
                .setSelection(androidx.core.util.Pair.create(startTime.getTime(), endTime.getTime()))
                .build();

        btnDateFilter.setOnClickListener(v -> {
            if (dateRangePicker != null) {
                dateRangePicker.show(getSupportFragmentManager(), "DATE_RANGE_PICKER");
            }
        });

        dateRangePicker.addOnPositiveButtonClickListener(selection -> {
            startTime = new Date(selection.first);
            endTime = new Date(selection.second);
            updateDateRangeButton();
            saveDateRange();
            loadData();
        });
    }

    private void showSendCommandDialog() {
        SendCommandDialog dialog = new SendCommandDialog(this, deviceId);
        dialog.show();
    }

    private void showUpdateFirmwareDialog() {
        new AlertDialog.Builder(this)
                .setTitle("更新固件")
                .setMessage("确定要更新设备固件吗？此操作可能需要一些时间。")
                .setPositiveButton("选择文件", (dialog, which) -> pickFirmwareFile())
                .setNegativeButton("取消", null)
                .show();
    }

    private void pickFirmwareFile() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("*/*");
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        String[] mimeTypes = {"application/octet-stream", "application/x-binary"};
        intent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes);
        startActivityForResult(Intent.createChooser(intent, "选择固件文件"), PICK_FIRMWARE_FILE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PICK_FIRMWARE_FILE && resultCode == RESULT_OK) {
            Uri uri = data.getData();
            if (uri != null) {
                uploadFirmware(uri);
            }
        }
    }

    private void uploadFirmware(Uri uri) {
        progressBar.setVisibility(View.VISIBLE);
        
        try {
            String fileName = getFileName(uri);
            RequestBody requestFile = RequestBody.create(MediaType.parse("application/octet-stream"), 
                    getFileFromUri(uri));
            MultipartBody.Part body = MultipartBody.Part.createFormData("firmware", fileName, requestFile);

            apiService.updateFirmware(device.getDeviceId(), body)
                    .enqueue(new Callback<ResponseBody>() {
                        @Override
                        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                            progressBar.setVisibility(View.GONE);
                            if (response.isSuccessful()) {
                                Toast.makeText(DeviceDetailActivity.this, "固件更新成功", Toast.LENGTH_SHORT).show();
                            } else {
                                Toast.makeText(DeviceDetailActivity.this, "固件更新失败", Toast.LENGTH_SHORT).show();
                            }
                        }

                        @Override
                        public void onFailure(Call<ResponseBody> call, Throwable t) {
                            progressBar.setVisibility(View.GONE);
                            Toast.makeText(DeviceDetailActivity.this, "网络错误: " + t.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    });
        } catch (Exception e) {
            progressBar.setVisibility(View.GONE);
            Toast.makeText(this, "文件处理错误: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    private String getFileName(Uri uri) {
        String result = null;
        if (uri.getScheme().equals("content")) {
            Cursor cursor = getContentResolver().query(uri, null, null, null, null);
            try {
                if (cursor != null && cursor.moveToFirst()) {
                    int columnIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
                    if (columnIndex != -1) {
                        result = cursor.getString(columnIndex);
                    }
                }
            } finally {
                if (cursor != null) {
                    cursor.close();
                }
            }
        }
        if (result == null) {
            result = uri.getPath();
            int cut = result.lastIndexOf(File.separator);
            if (cut != -1) {
                result = result.substring(cut + 1);
            }
        }
        return result;
    }

    private File getFileFromUri(Uri uri) throws IOException {
        InputStream inputStream = getContentResolver().openInputStream(uri);
        File tempFile = File.createTempFile("firmware", ".bin", getCacheDir());
        FileOutputStream outputStream = new FileOutputStream(tempFile);
        
        byte[] buffer = new byte[4096];
        int bytesRead;
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, bytesRead);
        }
        
        outputStream.close();
        inputStream.close();
        return tempFile;
    }

    private void showEditConfigDialog() {
        showLoading(true);
        apiService.getDeviceConfig(deviceId).enqueue(new Callback<DeviceConfig>() {
            @Override
            public void onResponse(Call<DeviceConfig> call, Response<DeviceConfig> response) {
                showLoading(false);
                if (response.isSuccessful() && response.body() != null) {
                    showConfigEditDialog(response.body());
                } else {
                    showError("加载配置失败");
                }
            }

            @Override
            public void onFailure(Call<DeviceConfig> call, Throwable t) {
                showLoading(false);
                showError("网络错误");
            }
        });
    }

    private void showConfigEditDialog(DeviceConfig config) {
        View dialogView = getLayoutInflater().inflate(R.layout.dialog_edit_config, null);
        // 设置配置编辑界面的初始值
        // ...

        new MaterialAlertDialogBuilder(this)
            .setTitle("编辑配置")
            .setView(dialogView)
            .setPositiveButton("保存", (dialog, which) -> {
                // 获取编辑后的配置值
                // 保存配置
                updateDeviceConfig(config);
            })
            .setNegativeButton("取消", null)
            .show();
    }

    private void updateDeviceConfig(DeviceConfig config) {
        showLoading(true);
        apiService.updateDeviceConfig(deviceId, config).enqueue(new Callback<DeviceConfig>() {
            @Override
            public void onResponse(Call<DeviceConfig> call, Response<DeviceConfig> response) {
                showLoading(false);
                if (response.isSuccessful()) {
                    showSuccess("配置更新成功");
                } else {
                    showError("配置更新失败");
                }
            }

            @Override
            public void onFailure(Call<DeviceConfig> call, Throwable t) {
                showLoading(false);
                showError("网络错误：" + t.getMessage());
            }
        });
    }

    private void showEditThresholdsDialog() {
        // 实现阈值编辑对话框
    }

    private void showLoading(boolean show) {
        progressBar.setVisibility(show ? View.VISIBLE : View.GONE);
    }

    private void showError(String message) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }

    private void showSuccess(String message) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_device_detail, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_control) {
            showDeviceControlDialog();
            return true;
        } else if (id == R.id.action_edit_device) {
            showEditDeviceDialog();
            return true;
        } else if (id == R.id.action_send_command) {
            showSendCommandDialog();
            return true;
        } else if (id == R.id.action_update_firmware) {
            showUpdateFirmwareDialog();
            return true;
        } else if (id == R.id.action_delete) {
            showDeleteConfirmDialog();
            return true;
        } else if (id == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void showDeleteConfirmDialog() {
        new AlertDialog.Builder(this)
                .setTitle("删除设备")
                .setMessage("确定要删除这个设备吗？此操作不可撤销。")
                .setPositiveButton("删除", (dialog, which) -> deleteDevice())
                .setNegativeButton("取消", null)
                .show();
    }

    private void deleteDevice() {
        if (device == null) return;

        progressBar.setVisibility(View.VISIBLE);
        apiService.deleteDevice(device.getId())
                .enqueue(new Callback<ResponseBody>() {
                    @Override
                    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                        progressBar.setVisibility(View.GONE);
                        if (response.isSuccessful()) {
                            Toast.makeText(DeviceDetailActivity.this, "设备已删除", Toast.LENGTH_SHORT).show();
                            setResult(RESULT_OK);
                            finish();
                        } else {
                            Toast.makeText(DeviceDetailActivity.this, "删除设备失败", Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onFailure(Call<ResponseBody> call, Throwable t) {
                        progressBar.setVisibility(View.GONE);
                        Toast.makeText(DeviceDetailActivity.this, "网络错误", Toast.LENGTH_SHORT).show();
                    }
                });
    }

    private void initWebSocket() {
        String token = SharedPreferencesManager.getInstance(this).getToken();
        if (token == null) {
            return;
        }

        WebSocketManager.getInstance(this).connect(token);
    }

    private void handleWebSocketMessage(String message) {
        // 处理 WebSocket 消息
        // 根据消息类型更新 UI
    }

    private void showEditDeviceDialog() {
        EditDeviceDialog dialog = new EditDeviceDialog(this, device);
        dialog.setOnDeviceUpdatedListener(updatedDevice -> {
            device = updatedDevice;
            updateDeviceInfo(updatedDevice);
        });
        dialog.show();
    }

    private void setupPagination() {
        btnPrevPage.setOnClickListener(v -> {
            if (deviceDataAdapter.hasPreviousPage()) {
                deviceDataAdapter.previousPage();
                updatePageInfo();
            }
        });

        btnNextPage.setOnClickListener(v -> {
            if (deviceDataAdapter.hasNextPage()) {
                deviceDataAdapter.nextPage();
                updatePageInfo();
            }
        });

        updatePageInfo();
    }

    private void updatePageInfo() {
        if (deviceDataAdapter != null && tvPageInfo != null) {
            int currentPage = deviceDataAdapter.getCurrentPage() + 1;
            int totalItems = deviceDataAdapter.getTotalItems();
            int itemsPerPage = deviceDataAdapter.getItemsPerPage();
            int totalPages = (int) Math.ceil((double) totalItems / itemsPerPage);
            
            String pageInfo = String.format("%d/%d", currentPage, totalPages);
            tvPageInfo.setText(pageInfo);
            
            // 更新翻页按钮状态
            btnPrevPage.setEnabled(deviceDataAdapter.hasPreviousPage());
            btnNextPage.setEnabled(deviceDataAdapter.hasNextPage());
        }
    }

    private void showDeviceControlDialog() {
        DeviceControlDialog dialog = new DeviceControlDialog(this, device.getDeviceId());
        dialog.show();
    }

    private void updateDateRangeButton() {
        if (btnDateFilter != null && startTime != null && endTime != null) {
            String dateRange = String.format("%s 至 %s",
                    DATE_RANGE_FORMAT.format(startTime),
                    DATE_RANGE_FORMAT.format(endTime));
            btnDateFilter.setText(dateRange);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (handler != null) {
            handler.removeCallbacksAndMessages(null);
        }
        if (webSocketClient != null) {
            webSocketClient.disconnect();
        }
        if (webSocket != null) {
            webSocket.close(1000, "Activity destroyed");
        }
        if (wsClient != null) {
            wsClient.dispatcher().executorService().shutdown();
        }
        // 移除WebSocket监听器
        WebSocketManager.getInstance(this).removeStatusListener(this);
        WebSocketManager.getInstance(this).removeDataListener(this);
    }

    private void setupRecyclerView() {
        deviceDataAdapter = new DeviceDataAdapter();
        deviceDataAdapter.setOnPageChangeListener((currentPage, totalPages) -> {
            if (tvPageInfo != null) {
                tvPageInfo.setText(String.format("%d/%d", currentPage, totalPages));
            }
            if (btnPrevPage != null) {
                btnPrevPage.setEnabled(deviceDataAdapter.hasPreviousPage());
            }
            if (btnNextPage != null) {
                btnNextPage.setEnabled(deviceDataAdapter.hasNextPage());
            }
        });
        recyclerView.setAdapter(deviceDataAdapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
    }

    private void loadData() {
        showLoading(true);
        loadDeviceData();
        loadHistoryData();
    }

    private void setupToolbar() {
        setSupportActionBar(toolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setTitle("设备详情");
        }
    }

    private void setupButtons() {
        btnPrevPage.setOnClickListener(v -> {
            deviceDataAdapter.previousPage();
            updatePageInfo();
        });

        btnNextPage.setOnClickListener(v -> {
            deviceDataAdapter.nextPage();
            updatePageInfo();
        });
    }

    private void setupDateRangePicker() {
        if (startTime == null || endTime == null) {
            return;
        }

        MaterialDatePicker<androidx.core.util.Pair<Long, Long>> dateRangePicker = MaterialDatePicker.Builder.dateRangePicker()
                .setTitleText("选择日期范围")
                .setSelection(androidx.core.util.Pair.create(startTime.getTime(), endTime.getTime()))
                .build();

        btnDateFilter.setOnClickListener(v -> {
            if (dateRangePicker != null) {
                dateRangePicker.show(getSupportFragmentManager(), "DATE_RANGE_PICKER");
            }
        });

        dateRangePicker.addOnPositiveButtonClickListener(selection -> {
            startTime = new Date(selection.first);
            endTime = new Date(selection.second);
            updateDateRangeButton();
            saveDateRange();
            loadData();
        });
    }

    private void loadDateRange() {
        SharedPreferences prefs = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
        long startTimeMillis = prefs.getLong(KEY_START_TIME, -1);
        long endTimeMillis = prefs.getLong(KEY_END_TIME, -1);
        
        if (startTimeMillis != -1 && endTimeMillis != -1) {
            startTime = new Date(startTimeMillis);
            endTime = new Date(endTimeMillis);
        }
    }

    private void saveDateRange() {
        if (startTime != null && endTime != null) {
            SharedPreferences prefs = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
            prefs.edit()
                .putLong(KEY_START_TIME, startTime.getTime())
                .putLong(KEY_END_TIME, endTime.getTime())
                .apply();
        }
    }

    private void connectWebSocket() {
        String token = SharedPreferencesManager.getInstance(this).getToken();
        if (token == null) {
            return;
        }

        WebSocketManager.getInstance(this).connect(token);
    }

    @Override
    public void onDeviceStatusChanged(String deviceId, String status, String lastHeartbeat) {
        if (deviceId.equals(this.deviceId)) {
            runOnUiThread(() -> {
                if (device != null) {
                    device.setStatus(status);
                    device.setLastHeartbeat(lastHeartbeat);
                    updateUI();
                }
            });
        }
    }

    @Override
    public void onDeviceDataUpdated(String deviceId, Double temperature, Double humidity) {
        if (deviceId.equals(this.deviceId)) {
            runOnUiThread(() -> {
                if (temperature != null) {
                    tvTemperature.setText(String.format("%.1f°C", temperature));
                }
                if (humidity != null) {
                    tvHumidity.setText(String.format("%.1f%%", humidity));
                }
            });
        }
    }

    private void updateDeviceStatus(JSONObject data) {
        try {
            String status = data.getString("status");
            String lastHeartbeat = data.getString("lastHeartbeat");
            Double temperature = data.has("temperature") ? data.getDouble("temperature") : null;
            Double humidity = data.has("humidity") ? data.getDouble("humidity") : null;

            // 更新状态显示
            tvDeviceStatus.setText(status.equals("online") ? "在线" : "离线");
            tvDeviceStatus.setBackgroundResource(status.equals("online") ? 
                R.color.colorStatusOnline : R.color.colorStatusOffline);

            // 更新最后心跳时间
            if (lastHeartbeat != null) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
                Date date = sdf.parse(lastHeartbeat);
                if (date != null) {
                    tvLastHeartbeat.setText(sdf.format(date));
                }
            }

            // 更新实时数据
            if (temperature != null) {
                tvTemperature.setText(String.format("%.1f°C", temperature));
            }
            if (humidity != null) {
                tvHumidity.setText(String.format("%.1f%%", humidity));
            }
        } catch (JSONException | ParseException e) {
            e.printStackTrace();
        }
    }

    private void updateDeviceData(JSONObject data) {
        try {
            Double temperature = data.has("temperature") ? data.getDouble("temperature") : null;
            Double humidity = data.has("humidity") ? data.getDouble("humidity") : null;

            if (temperature != null) {
                tvTemperature.setText(String.format("%.1f°C", temperature));
            }
            if (humidity != null) {
                tvHumidity.setText(String.format("%.1f%%", humidity));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void loadDeviceInfo() {
        apiService.getDevice(deviceId).enqueue(new Callback<Device>() {
            @Override
            public void onResponse(Call<Device> call, Response<Device> response) {
                if (response.isSuccessful() && response.body() != null) {
                    device = response.body();
                    runOnUiThread(() -> updateUI());
                } else {
                    runOnUiThread(() -> 
                        Toast.makeText(DeviceDetailActivity.this, 
                            "加载设备信息失败", 
                            Toast.LENGTH_SHORT).show()
                    );
                }
            }

            @Override
            public void onFailure(Call<Device> call, Throwable t) {
                runOnUiThread(() -> 
                    Toast.makeText(DeviceDetailActivity.this, 
                        "加载设备信息失败: " + t.getMessage(), 
                        Toast.LENGTH_SHORT).show()
                );
            }
        });
    }
} 